<template>
  <div class="log-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索日志内容/操作者"
        clearable
        @clear="handleSearch"
        @input="handleSearch"
        style="width: 300px"
      >
        <template #prefix>
          <i class="el-icon-search"></i>
        </template>
      </el-input>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd"
        @change="handleSearch"
        style="width: 300px; margin-left: 10px"
      />
    </div>

    <!-- 日志表格 -->
    <el-table
      v-loading="loading"
      :data="filteredLogs"
      border
      style="width: 100%"
    >
      <el-table-column
        prop="id"
        label="ID"
        width="220"
      />
      <el-table-column
        label="操作者"
        width="120"
      >
        <template #default="{ row }">
          <span>{{ getUserNickname(row.userId) || row.userId || '系统' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="detail"
        label="日志内容"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        prop="createTime"
        label="操作时间"
        width="180"
      >
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="120"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            class="delete-btn"
            @click="handleDelete(row)"
            plain
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 统计信息卡片 -->
    <div class="statistics-cards">
      <el-card class="statistics-card">
        <template #header>
          <div class="card-header">
            <span>今日日志数</span>
          </div>
        </template>
        <div class="card-content">
          <span class="number">{{ statistics.todayCount }}</span>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { Message, MessageBox } from 'element-ui'
import logService from '@/services/log.service'
import userService from '@/services/user.service'

export default {
  name: 'LogView',
  data() {
    return {
      logs: [],
      users: [],
      loading: false,
      searchQuery: '',
      dateRange: [],
      
      statistics: {
        todayCount: 0,
        errorCount: 0,
        warningCount: 0
      }
    }
  },
  computed: {
    // 过滤日志列表
    filteredLogs() {
      let result = this.logs

      // 日期范围过滤
      if (this.dateRange && this.dateRange.length === 2) {
        const startDate = new Date(this.dateRange[0])
        const endDate = new Date(this.dateRange[1])
        endDate.setHours(23, 59, 59, 999)

        result = result.filter(log => 
          {
          const createTime = new Date(log.createTime)
          return createTime >= startDate && createTime <= endDate
        })
      }

      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(log => 
          (log.detail && log.detail.toLowerCase().includes(query)) ||
          (log.userId && log.userId.toString().toLowerCase().includes(query))
        )
      }

      return result
    }
  },
  mounted() {
    this.fetchLogs()
    this.fetchUsers()
  },
  methods: {
    // 获取日志列表
    async fetchLogs() {
      try {
        this.loading = true
        const response = await logService.getLogs()
        console.log('日志API响应:', response)
        
        if (response && response.code === 200) {
          // 处理后端返回的数据
          let data = response.data
          if (data && Array.isArray(data)) {
            // 数据本身就是数组
            console.log('数据本身就是数组格式:', data)
          } else if (data && typeof data === 'object') {
            // 检查Entity Framework的$values属性
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
              console.log('找到Entity Framework格式的日志数组数据:', data)
            } else {
              // 尝试从其他可能的属性中获取数组
              const possibleArrayKeys = ['items', 'list', 'logs', 'data', 'result']
              for (const key of possibleArrayKeys) {
                if (Array.isArray(data[key])) {
                  data = data[key]
                  console.log(`找到日志数组数据在属性 ${key}:`, data)
                  break
                }
              }
              // 如果还是找不到数组，设置为空数组
              if (!Array.isArray(data)) {
                console.warn('无法找到日志数组数据，设置为空数组')
                data = []
              }
            }
          } else {
            // 如果data不是对象或数组，设置为空数组
            data = []
          }
          
          this.logs = data || []
          console.log('日志列表:', this.logs)
          console.log('日志列表长度:', this.logs.length)
          // 计算统计信息
          this.calculateStatistics()
        } else {
          console.error('API返回错误:', response)
          this.logs = []
          Message.error(response?.message || '获取日志列表失败')
        }
      } catch (error) {
        console.error('获取日志列表失败:', error)
        console.error('错误详情:', {
          message: error?.message,
          response: error?.response,
          status: error?.response?.status,
          data: error?.response?.data
        })
        
        // 安全的错误消息处理
        let errorMessage = '获取日志列表失败'
        if (error?.response?.data?.message) {
          errorMessage = error.response.data.message
        } else if (error?.message) {
          errorMessage = error.message
        }
        
        Message.error(errorMessage)
        this.logs = []
      } finally {
        this.loading = false
      }
    },

    // 计算统计信息
    calculateStatistics() {
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      let todayCount = 0
      
      this.logs.forEach(log => {
        const createTime = new Date(log.createTime)
        if (createTime >= today) {
          todayCount++
        }
      })
      
      this.statistics.todayCount = todayCount
      this.statistics.errorCount = 0 // 暂时设为0，因为没有level字段
      this.statistics.warningCount = 0 // 暂时设为0，因为没有level字段
    },

    // 搜索
    handleSearch() {
      // 搜索逻辑已通过计算属性实现
    },

    // 删除日志
    async handleDelete(row) {
      try {
        await MessageBox.confirm('确定要删除这条日志记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await logService.deleteLog(row.id)
        Message.success('删除成功')
        await this.fetchLogs()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除日志失败:', error)
          Message.error(error?.response?.data?.message || '删除失败')
        }
      }
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return d.toLocaleString()
    },

    // 格式化JSON
    formatJson(json) {
      if (!json) return ''
      try {
        return JSON.stringify(JSON.parse(json), null, 2)
      } catch (e) {
        return json
      }
    },

    // 获取用户昵称
    getUserNickname(userId) {
      if (!userId) return '-'
      console.log('getUserNickname - 查找用户ID:', userId)
      console.log('getUserNickname - 当前用户列表:', this.users)
      
      // 尝试多种可能的字段名匹配
      const user = this.users.find(u => 
        u.UserId === userId || 
        u.userId === userId || 
        u.id === userId
      )
      
      if (!user) {
        console.log('getUserNickname - 未找到用户:', userId)
        return '未知用户'
      }
      
      console.log('getUserNickname - 找到用户:', user)
      return user.Nickname || user.nickname || '未知用户'
    },

    // 获取用户列表
    async fetchUsers() {
      try {
        const response = await userService.getUsers()
        console.log('fetchUsers - 用户API原始响应:', response)
        
        if (response && response.code === 200) {
          let data = response.data
          if (data && typeof data === 'object') {
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
              console.log('fetchUsers - 找到Entity Framework格式的用户数组数据:', data)
            } else {
              const possibleArrayKeys = ['items', 'list', 'users', 'data', 'result']
              for (const key of possibleArrayKeys) {
                if (Array.isArray(data[key])) {
                  data = data[key]
                  console.log(`fetchUsers - 找到用户数组数据在属性 ${key}:`, data)
                  break
                }
              }
              if (!Array.isArray(data)) {
                data = []
              }
            }
          }
          this.users = data
          console.log('fetchUsers - 处理后的用户列表:', this.users)
          console.log('fetchUsers - 用户列表长度:', this.users.length)
          
          // 打印第一个用户的字段结构
          if (this.users.length > 0) {
            console.log('fetchUsers - 第一个用户的字段结构:', Object.keys(this.users[0]))
            console.log('fetchUsers - 第一个用户的完整数据:', this.users[0])
          }
        }
      } catch (error) {
        Message.error('获取用户列表失败: ' + error.message)
      }
    }
  }
}
</script>

<style scoped>
.log-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}

.log-detail {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.detail-item .label {
  width: 100px;
  color: #606266;
  font-weight: bold;
}

.detail-item .content {
  flex: 1;
  white-space: pre-wrap;
  word-break: break-all;
}

.detail-item .content pre {
  margin: 0;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-family: monospace;
}

.statistics-cards {
  margin-top: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.statistics-card {
  text-align: center;
}

.card-header {
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
}

.card-content {
  padding: 20px 0;
}

.card-content .number {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.card-content .number.error {
  color: #F56C6C;
}

.card-content .number.warning {
  color: #E6A23C;
}
</style> 